package com.dtd.market.utils;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;

public class JsonUtils {
	private static ObjectMapper m;
	static {
		m = new ObjectMapper();
		// 设置反序列化时忽略JSON字符串中存在而Java对象实际没有的属性
		m.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
				false);

	}
	private static JsonFactory jf = new JsonFactory();

	public static <T> T fromJson(String jsonAsString, Class<T> pojoClass){
		try{
			return m.readValue(jsonAsString, pojoClass);
		}catch(Exception e){
			throw new RuntimeException(e);
		}		
	}

	public static <T> T fromJson(FileReader fr, Class<T> pojoClass){
		try{
			return m.readValue(fr, pojoClass);
		}catch(Exception e){
			throw new RuntimeException(e);
		}		
	}

	public static <T> List<T> listFromJson(String jsonAsString,Class<T> pojoClass){		
		try{
			TypeFactory t = TypeFactory.defaultInstance(); 
			List<T> beanList = m.readValue(jsonAsString,
					t.constructCollectionType(ArrayList.class,pojoClass));
			return beanList;
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}

	public static <T> Map<String, T> mapFromJson(String jsonAsString,
			Class<T> pojoClass){		
		try{
			TypeFactory t = TypeFactory.defaultInstance();
			Map<String, T> beanMap = m.readValue(jsonAsString,
					t.constructMapType(HashMap.class, String.class,pojoClass));
			return beanMap;
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}

	public static String toJson(Object pojo, boolean prettyPrint){
		try{
			StringWriter sw = new StringWriter();
			JsonGenerator jg = jf.createJsonGenerator(sw);
			if (prettyPrint) {
				jg.useDefaultPrettyPrinter();
			}
		
			m.writeValue(jg, pojo);
			jg.close();
			return sw.toString();
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}

	public static void toJson(Object pojo, FileWriter fw, boolean prettyPrint){

		try{
			JsonGenerator jg = jf.createJsonGenerator(fw);
			if (prettyPrint) {
				jg.useDefaultPrettyPrinter();
			}
			
			m.writeValue(jg, pojo);
			jg.close();
		}catch(Exception e){
			throw new RuntimeException(e);
		}	
	}

}